package com.lvyq.qrobot.controller;


import cn.hutool.json.JSONUtil;
import com.lvyq.qrobot.common.PostType;
import com.lvyq.qrobot.common.UrlConstant;
import com.lvyq.qrobot.entity.UserMsg;
import com.lvyq.qrobot.locadata.OrderCode;
import com.lvyq.qrobot.mapper.UserMsgMapper;
import com.lvyq.qrobot.model.receive.ReceiveMsg;
import com.lvyq.qrobot.model.send.SendParam;
import com.lvyq.qrobot.service.MsgDispenseService;
import com.lvyq.qrobot.util.CommonUtil;
import com.lvyq.qrobot.util.HttpClientUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author lvyq  主入口
 * @version 1.0
 * Create by 2024-05-27 15:10
 */
@RestController
@RequestMapping
public class MainController {


    @Resource
    public MsgDispenseService msgDispenseService;

    @Resource
    public UserMsgMapper userMsgMapper;

    
    /**
     * @description 消息接收
     * @author lvyq
     * @param[1] request
     * @throws 
     * @time 2024-05-31 10:11
     */
    @RequestMapping("/")
    public void main(HttpServletRequest request)  {
        StringBuilder body = new StringBuilder();
        try (BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                body.append(line); // 根据需要添加换行符
            }
            if (body.length() > 0) {
                SimpleDateFormat format  = new SimpleDateFormat("yyyy-MM-dd");
                ReceiveMsg vo = JSONUtil.toBean(body.toString(), ReceiveMsg.class);
                System.out.println("接受消息》》》》》"+body.toString());
                UserMsg userMsg = new UserMsg();
                userMsg.setUserId(vo.userId);
                userMsg.setUserName(vo.getSender().nickname);
                userMsg.setContent(vo.message);
                userMsg.setCreateTime(format.format(new Date()));
                userMsg.setGroupId(vo.groupId);
                userMsgMapper.insert(userMsg);
                if (PostType.MESSAGE.equals(vo.postType)){
                    msgDispenseService.dispenseMsg(vo);
                } else if (PostType.NOTICE.equals(vo.postType)){
                    //入群消息
                    SendParam param = new SendParam();
                    param.setGroup_id(vo.groupId);
                    String content= OrderCode.TELL_JOKES.content.replace(
                            "{1}", UrlConstant.Audio_WELCOME+"welcome.mp3"
                    );
                    param.setMessage(content);
                   // HttpClientUtil.doPostJson(UrlConstant.send_group_msg,param);
                    System.out.println("入群消息");
                }

            }
        } catch (IOException e) {
            System.out.println("系统异常");
        }
    }


}
